// src/pages/webIndex/webIndex.js
import getIn from '../../../yali-sdk/utils/getIn';
import { SUCCESS } from '../../../yali-sdk/utils/success';
import { FAIL } from '../../../yali-sdk/utils/fail';
import { SHOP_LIST, CATERINNG_GOODS_LIST, POP_SHOP, HOTEL_GOODS_LIST, GET_LOCATION_LIST, EXHIBITION_SHOP } from '../pathUrl'
import { banner, banners, bannert } from './images.js';
import { showFail, showSuccess } from '../../config/common';
import getLocation from '../../common/location';
import fetchShopCate from '../../../yali-sdk/business/shop/fetchShopCate';
import webIndexBanner from '../../../yali-sdk/business/shop/webIndexBanner';
import { addNotifier, removeNotifier, notify } from '../../../yali-sdk/utils/NotifyRegistryCenter';
import ActionDispatcher from '../../../yali-sdk/utils/ActionDispatcher';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    location: '定位中...',
    shopText: '',
    imgUrls: [banner, banners, bannert],
    menu:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    const locationText = getApp().globalData.address;
    addNotifier && addNotifier('updateLocation', (location) => {
      this.setData({ location });
      this.fetchData();
    }, this);
    locationText && this.setData({ location: locationText });
    wx.showLoading({
      title: '加载中...',
    });
    if (!global.ActionDispatcher) {
      const Core = {
        apiBase: 'https://www.nlido.com',
        domain: 'mp.mini1.xinpear.net'
      }
      const actionDispatcher = new ActionDispatcher(Core);
      global.ActionDispatcher = actionDispatcher;
      this.fetchData();
      this.bannerList();
    } else {
      this.fetchData();
      this.bannerList();
    }
  },
  onUnload() {
    removeNotifier('updateLocation');
  },
  onPullDownRefresh() {
    this.fetchData();
    this.bannerList();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  // 输入店铺名称
  onChange(e) {
    this.setData({
      shopText: e.detail.value
    })
  },
  // 搜索店铺
  searchShop(e) {
    const { shopText } = this.data;
    const queryString = `shopText=${shopText}`;
    if (shopText != '') {
      global.navigateHelper.redirectTo({
        pathname: SHOP_LIST,
        queryString,
      });
    }
  },
  // 首页banner
  bannerList() {
    const params = {};
    global.ActionDispatcher.execute(webIndexBanner, params, (status, result) => {
      if (status == SUCCESS) {
        let imgUrls = [];
        const bannerList = getIn(result.data, ['banner_pictures']);
        bannerList && bannerList.map && bannerList.map((x, i) => {
          imgUrls[i] = x.picture_url;
        })
        this.setData({ imgUrls });
      } else if (status == FAIL){
        showFail(result.msg);
      }
    });
  },
  // 首页店铺分类列表
  fetchData() {
    const app = getApp().globalData;
    const params = {
      is_index: true,
      is_with_shops: true,
      lng: app.longitude,
      lat: app.latitude,
    }
    global.ActionDispatcher.execute(fetchShopCate, params, (status, result) => {
      if (status == SUCCESS) {
        const shopCate = getIn(result.data, ['list']);
        let menu = [];
        shopCate && shopCate.map((x) => {
          const item = {
            id: x.id,
            name: x.name,
            icon: x.icon,
          }
          menu.push(item)
        });
        menu = this.formatArray(menu);
        this.setData({ menu, shopCate });
        wx.stopPullDownRefresh();
        wx.hideLoading();
      } else if(status == SUCCESS) {
        wx.stopPullDownRefresh();
        wx.hideLoading();
      }
    })
  },
  // 处理menu数组
  formatArray(arr) {
    let begin = 0,
    end = begin + 8;
    let result = [],
    arrLength = arr.length;
    if (end >= arrLength) result.push(arr);
    while(end < arrLength) {
      result.push(arr.slice(begin, end));
      begin = begin + 8;
      end = begin + 8;
      if (end > arrLength) {
        end = arrLength;
        result.push(arr.slice(begin, end));
        break;
      }
    }
    return result;
  },
  // 点击分类跳转店铺列表
  toShopList(e) {
    const cate_id = getIn(e.currentTarget, ['id']);
    const queryString = `cate_id=${cate_id}`;
    global.navigateHelper.navigateTo({
      pathname: SHOP_LIST,
      queryString,
    });
  },
  // 点击进入产品列表
  toShop(e) {
    const id = getIn(e.currentTarget, ['id']);
    const cate_id = getIn(e.currentTarget, ['dataset', 'cate_id']);
    const template = getIn(e.currentTarget, ['dataset', 'template']);
    const queryString = `id=${id}&cate_id=${cate_id}`;
    switch (Number(template)) {
      case 1: {// 餐饮店铺
        global.navigateHelper.navigateTo({
          pathname: CATERINNG_GOODS_LIST,
          queryString,
        });
        break;
      }
      case 2: {// 酒店店铺
        global.navigateHelper.navigateTo({
          pathname: HOTEL_GOODS_LIST,
          queryString,
        });
        break;
      }
      case 3: {// 展示型店铺
        global.navigateHelper.navigateTo({
          pathname: EXHIBITION_SHOP,
          queryString,
        });
        break;
      }
      default: {// 其他店铺
        global.navigateHelper.navigateTo({
          pathname: POP_SHOP,
          queryString,
        });
        break;
      }
    }
  },
  // 点击进入location列表
  toLocationList() {
    global.navigateHelper.navigateTo({
      pathname: GET_LOCATION_LIST
    });
  }
})